import router from './index';
import store from '@/store';
// cookie
import { getToken, getActiveRouterPath, setActiveRouterPath } from "@/utils/cookies";

// 挂载路由导航守卫
// beforeEach是vue的一个全局钩子函数，在路由发生改变时触发
router.beforeEach((to, from, next) => {
  // console.log("to路由path：",to.path)
  // 路由发生改变修改页面title
  if (to.meta.title) {
    document.title = to.meta.title + " - 欢迎进入爆爆box后台管理系统";
  }
  if (!getToken()) { // 没有token，或者token为空
    // console.log("没有token",getToken())
    if (to.path !== "/login") {
      next({ path: '/login' });
    } else {
      next();
    }
  } else {  // 有token
    if (store.state.permission.dynamic_router.length === 0) {   // vuex中没有动态路由，说明是第一次登录，或登录已失效，清除了路由
      /**
       * 请求后端api，获取路由菜单
       */
      store.dispatch("permission/getRouterAction").then(response => {
        // 获取动态路由
        const dynamic_router_data = store.getters["permission/dynamic_router"];
        // 获取静态路由
        const static_router_data = router.options.routes;
        // 更新静态路由
        router.options.routes = static_router_data.concat(dynamic_router_data);
        // 更新动态路由
        dynamic_router_data.forEach(item => {
          router.addRoute(item);
        });
        // 确认进入下一个路由
        next({
          ...to,
          replace: true
        });
      })
    } else {  // 有动态路由
      // 如果访问登陆页面，直接跳转保存的当前活动路由
      let activeRouterPath = getActiveRouterPath()
      // console.log("当前活动路由：", activeRouterPath)
      if (
        (to.path === "/login" && typeof (activeRouterPath) == "undefined") ||
        (to.path === "/login" && typeof (activeRouterPath) != "undefined" && activeRouterPath === "/login") ||
        (to.path !== "/login" && typeof (activeRouterPath) == "undefined") ||
        (to.path !== "/login" && typeof (activeRouterPath) != "undefined" && activeRouterPath === "/login")
      ) {
        // setActiveRouterPath("/workbench")
        // next({ path: "/workbench" })
        let firstPath = window.sessionStorage.getItem("firstPath")
        setActiveRouterPath(firstPath)
        next({ path: firstPath })
      } else if (to.path === "/login" && typeof (activeRouterPath) != "undefined" && activeRouterPath !== "/login") {
        setActiveRouterPath(activeRouterPath)
        next({ path: activeRouterPath })
      } else {
        let flagStr = "-page"
        let path = to.path
        if (path.indexOf(flagStr) === -1) {  // 不包含
          setActiveRouterPath(path)
        } else {  // 包含
          // 最后一个‘/’出现的位置
          let position = path.lastIndexOf("/")
          let savePath = path.substring(0, position)
          setActiveRouterPath(savePath)
        }
        next()
      }

    }
  }

});


// 全局后置守卫
router.afterEach((to, from) => { })